package com.Nuyoah.demo01.service;

import com.Nuyoah.demo01.DTO.common.ChatRequest;
import com.Nuyoah.demo01.DTO.common.ChatResponse;
import com.Nuyoah.demo01.DTO.common.Message;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Service
public class DeepSeekService {

    private final WebClient webClient;

    public DeepSeekService(
            @Value("${deepseek.base-url}") String baseUrl,
            @Value("${deepseek.api-key}") String apiKey) {
        this.webClient = WebClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader("Authorization", "Bearer " + apiKey)
                .build();
    }

    // 1. 非流式
    public Mono<String> chat(String prompt) {
        ChatRequest req = new ChatRequest(
                "deepseek-chat",
                List.of(new Message("user", prompt)),
                0.7,
                2048,
                false
        );
        return webClient.post()
                .uri("/chat/completions")
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(req)
                .retrieve()
                .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(),
                        response -> response.bodyToMono(String.class)
                                .flatMap(errorBody -> {
                                    System.err.println("API调用失败: " + errorBody);
                                    return Mono.error(new RuntimeException("API调用失败: " + response.statusCode()));
                                }))
                .bodyToMono(ChatResponse.class)
                .map(this::extractContentFromResponse)
                .onErrorResume(Exception.class, e -> {
                    System.err.println("处理响应时发生错误: " + e.getMessage());
                    return Mono.just("请求失败: " + e.getMessage());
                });
    }

    // 2. 流式 SSE（Server-Sent Events）
    public Flux<String> chatStream(String prompt) {
        ChatRequest req = new ChatRequest(
                "deepseek-chat",
                List.of(new Message("user", prompt)),
                0.7,
                2048,
                true
        );
        return webClient.post()
                .uri("/chat/completions")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.TEXT_EVENT_STREAM)
                .bodyValue(req)
                .retrieve()
                .bodyToFlux(String.class)   // 先按字符串流
                .filter(line -> line.startsWith("data: "))
                .map(line -> line.substring(6))
                .filter(data -> !data.equals("[DONE]"))
                .map(data -> {
                    try {
                        return extractContentFromStreamData(data);
                    } catch (Exception e) {
                        System.err.println("解析流式数据失败: " + e.getMessage());
                        return null; // 返回null以便后续过滤
                    }
                })
                .filter(chunk -> chunk != null && !chunk.isEmpty());
    }

    /**
     * 从非流式响应中提取内容
     */
    private String extractContentFromResponse(ChatResponse response) {
        if (response == null || response.choices() == null || response.choices().isEmpty()) {
            System.err.println("响应格式异常: choices为空或不存在");
            return "抱歉，未能获取有效的响应内容";
        }
        
        ChatResponse.Choice choice = response.choices().get(0);
        if (choice == null) {
            System.err.println("响应格式异常: choice为null");
            return "抱歉，未能获取有效的选择项";
        }
        
        // 非流式响应使用message字段
        Message message = choice.message();
        if (message == null || message.getContent() == null) {
            System.err.println("响应格式异常: message或content为null");
            return "抱歉，未能获取有效的内容";
        }
        
        return message.getContent();
    }

    /**
     * 从流式响应中提取内容
     */
    private String extractContentFromStreamData(String data) {
        try {
            ChatResponse response = new com.fasterxml.jackson.databind.ObjectMapper()
                    .readValue(data, ChatResponse.class);
            return extractContentFromStreamResponse(response);
        } catch (Exception e) {
            System.err.println("JSON解析失败: " + e.getMessage());
            return null;
        }
    }

        /**
     * 从流式响应中提取内容
     */
    private String extractContentFromStreamResponse(ChatResponse response) {
        if (response == null || response.choices() == null || response.choices().isEmpty()) {
            return null;
        }
        
        ChatResponse.Choice choice = response.choices().get(0);
        if (choice == null) {
            return null;
        }
        
        // 流式响应使用delta字段
        ChatResponse.Delta delta = choice.delta();
        if (delta == null || delta.content() == null || delta.content().isEmpty()) {
            return null;
        }
        
        return delta.content();
    }
}
